import { login, logout, getInfo } from '@/api/acl/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
// 引入项目中的常量路由  异步路由 任意路由
import router, { resetRouter, constantRoutes, asyncRoutes, anyRoute } from '@/router'

const getDefaultState = () => {
  return {
    // 令牌
    token: getToken(),
    // 用户名字
    name: '',
    // 用户头像
    avatar: '',
    // 按钮的权限
    buttons: [],
    //服务器异步路由信息
    routes: [],
    // 角色信息
    roles: [],
    // 最终用户需要展示的全部的路由信息 【常量 任意  异步】
    userResultRoute: [],
  }
}


const findUserAsyncRoute = (asyncRoutes, routes) => {
  // 过滤出当前用户有哪些异步路由
  let result = asyncRoutes.filter(item => {
    // 代表是有的
    if (routes.indexOf(item.name) != -1) {
      // 有子路由使用递归
      if (item.children && item.children.length > 0) {
        item.children = findUserAsyncRoute(item.children, routes)
      }
      return true;
    }
  })

  // 返回最终值
  return result;
  // console.log(result)
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  // 用户信息
  SET_USERINFO: (state, user) => {
    // console.log(user)
    state.name = user.name;
    state.avatar = user.avatar;
    state.roles = user.roles;
    state.routes = user.routes;
    state.buttons = user.buttons;
  },
  // 当亲用户全部路由的结果
  SET_USERRESULTROUTE: (state, asyncResult) => {

    // 需要展示全部路由
    state.userResultRoute = state.userResultRoute.concat(constantRoutes,asyncResult,anyRoute)

    // 需要动态给route添加动态路由
    router.addRoutes(state.userResultRoute)

  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password }).then(response => {
        const { data } = response
        commit('SET_TOKEN', data.token)
        // 持久化存储token -> cookie
        setToken(data.token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        const { data } = response

        // console.log(response)

        if (!data) {
          return reject('Verification failed, please Login again.')
        }

        // 获取用户名 头像 按钮权限  菜单权限  角色信息
        // const { name, avatar, buttons, routes, roles } = data;
        commit('SET_USERINFO', data)

        // 计算出当前用户全部路由结果
        commit('SET_USERRESULTROUTE', findUserAsyncRoute(asyncRoutes, data.routes))

        // commit('SET_NAME', name)
        // commit('SET_AVATAR', avatar)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        removeToken() // must remove  token  first
        resetRouter()
        commit('RESET_STATE')
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}


export default {
  namespaced: true,
  state,
  mutations,
  actions
}

